package com.example.demo.juc;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * 实现一个容器，提供两个方法，add，size 写两个线程，线程1添加10个元素到容器中，线程2实现监控元素的个数，当个数到5个时，线程2给出提示并结束
 */
public class CountDownLatchTest {
    volatile List<Integer> list = new ArrayList<>();

    public void add(int i){
        list.add(i);
    }

    public int getSize(){
        return list.size();
    }

//    public static void main(String[] args) {
//        CountDownLatchTest countDownLatchTest = new CountDownLatchTest();
//        Object lock = new Object();
//
//        new Thread(()->{
//            synchronized (lock){
//                System.out.println("t1启动");
//                if(countDownLatchTest.getSize() != 5){
//                    try {
//                        lock.wait();
//                        System.out.println("t1结束");
//                    }catch (InterruptedException e){
//                        e.printStackTrace();
//                    }
//                }
//                lock.notify();
//            }
//        },"t1").start();
//
//        new Thread(()->{
//            synchronized (lock){
//                System.out.println("t2启动");
//                for (int i = 0; i < 9; i++) {
//                    countDownLatchTest.add(i);
//                    System.out.println("t2添加元素" + i);
//                    if(countDownLatchTest.getSize() == 5){
//                        lock.notify();
//                        try {
//                            lock.wait();
//                        }catch (InterruptedException e){
//                            e.printStackTrace();
//                        }
//                    }
//                }
//            }
//        },"t2").start();
//    }


    public static void main(String[] args) {
        CountDownLatchTest countDownLatchTest = new CountDownLatchTest();

        CountDownLatch countDownLatch = new CountDownLatch(1);

        new Thread(()->{
            System.out.println("t1启动");
            if(countDownLatchTest.getSize() != 5){
                try {
                    countDownLatch.await();
                    System.out.println("t1结束");
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        },"t1").start();

        new Thread(()->{
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("t2启动");
            for (int i = 0; i < 9; i++) {
                countDownLatchTest.add(i);
                System.out.println("t2添加元素" + i);
                if(countDownLatchTest.getSize() == 5){
                    countDownLatch.countDown();
                }
            }
        },"t2").start();
    }
}
